package com.leyou.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.domain.Permission;
import com.leyou.dto.PermissionDTO;
import com.leyou.mapper.ListMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class ListService {

    @Autowired
    private ListMapper listMapper;

    /**
     * 分页排序 搜索查询
     * @param page 当前页
     * @param rows 每页的行数
     * @return
     */
    public PageResult<PermissionDTO> queryListByPage(Integer page, Integer rows) {
        //分页
        PageHelper.startPage(page,rows);
        //查询用户
        List<Permission> permissions = listMapper.selectAll();
        //解析分页结果
        PageInfo<Permission> pageInfo = new PageInfo<>(permissions);
        //将对象转换成DTO
        List<PermissionDTO> permissionDTOS = BeanHelper.copyWithCollection(permissions, PermissionDTO.class);
        //返回
        return new PageResult<>(pageInfo.getTotal(),permissionDTOS);
    }

    public List<PermissionDTO> findPermissionByParentId(Long pid) {
        Permission record = new Permission();
        record.setParentId(pid);
        List<Permission> permissionList = listMapper.select(record);
        if (CollectionUtils.isEmpty(permissionList)){
            throw new LyException(503,"权限不存在！");
        }
        return BeanHelper.copyWithCollection(permissionList,PermissionDTO.class);
    }

    public List<PermissionDTO> findPermissionById(Long pid) {
        List<Permission> permissions = listMapper.selectPermission(pid);
        if (CollectionUtils.isEmpty(permissions)){
            throw new LyException(503,"权限不存在！");
        }
        return BeanHelper.copyWithCollection(permissions,PermissionDTO.class);
    }

}
